package leetcode.p220;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: trtan
 * @create: 2021-04-20 16:51
 * @description:
 **/
public class ContainsDuplicateThree {
    public static void main(String[] args) {
        System.out.println(new ContainsDuplicateThree().containsNearbyAlmostDuplicate(new int[]{2147483647,-1,2147483647}, 1, 2147483647));
    }

    long getId(int x, long t) {
        if (x < 0) {
            return (x - t) / (t + 1);
        } else {
            return x / (t + 1);
        }
    }
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        Map<Long, Long> map = new HashMap<>(16);
        for (int i = 0; i < nums.length; i++) {
            long id = getId(nums[i], t);
            System.out.println(i + ", " + id);
            if (map.containsKey(id)) {
                return true;
            }
            if (map.containsKey(id - 1) && Math.abs(nums[i] - map.get(id - 1)) <= t) {
                return true;
            }

            if (map.containsKey(id + 1) && Math.abs(nums[i] - map.get(id + 1)) <= t) {
                return true;
            }

            map.put(id, (long) nums[i]);

            if (i >= k) {
                map.remove(getId(nums[i - k], t));
            }
        }
        return false;
    }
}
